package longrise.phone.com.bjjt_henan.Utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RatingBar;

import com.baidu.mapapi.model.CoordUtil;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.inner.Point;
import com.longrise.android.util.Util;
import com.longrise.bjjt.util.FileUtils;
import com.longrise.bjjt.util.UiUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import longrise.phone.com.bjjt_henan.R;

/**
 * Created by Administrator on 2016/5/13.
 */
public class CommontUtils {
    public static SimpleDateFormat dateSimple = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    public static void deleteFile(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }

    // bitmap转byte[]
    public static byte[] BitmaptoBytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
        return baos.toByteArray();
    }

    /**
     * Bitmap 转化为序列化的字符
     */
    public static String Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return com.longrise.LEAP.Base.IO.JSONSerializer.getInstance()
                .Serialize(baos.toByteArray());
    }

    /**
     * 返回系统当前时间 :xxxx年xx月xx日 hh:mm:ss
     *
     * @return
     */
    public static String getNowTime() {
        try {
            return dateSimple.format(new Date()) + "";
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 将时间字符串转化为时间戳
     *
     * @param time
     * @return
     */
    public static long getTimeStr(String time) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.parse(time).getTime();
    }

    /**
     * 改变部分字体的颜色
     *
     * @param text：字符串
     * @param strs：变色的字符集合
     * @param colors：颜色的集合
     * @return
     */
    /*public static CharSequence changeStrColor(String text, String[] strs, int[] colors) {
        if (strs.length > colors.length) {
            return text;
        }
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        for (int i = 0; i < strs.length; i++) {
            int color = colors[i];
            String indexStr = strs[i];
            int start = text.indexOf(indexStr);
            int end = start + indexStr.length();
            builder.setSpan(new ForegroundColorSpan(color), start, end,
                    Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        return builder;
    }*/

    /**
     * 改变部分字体的颜色
     *
     * @param text：字符串
     * @param indexStr：变色的字符
     * @param color：变色的字符颜色
     * @return
     */
    public static CharSequence changeStrColor(String text, String indexStr, Integer color) {
        if (null == text || null == indexStr) {
            return text;
        }
        int start = text.indexOf(indexStr);
        if (start < 0) {
            return text;
        }
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        int end = start + indexStr.length();
        builder.setSpan(new ForegroundColorSpan(color), start, end,
                Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        return builder;
    }

    /**
     * 获取责任类型
     *
     * @param duty
     * @return
     */
    public static String getDutyStr(String duty) {
        if (TextUtils.equals(duty, "0")) {
            return "全责";
        } else if (TextUtils.equals(duty, "1")) {
            return "无责";
        } else if (TextUtils.equals(duty, "2")) {
            return "同责";
        } else if (TextUtils.equals(duty, "3")) {
            return "主责";
        } else if (TextUtils.equals(duty, "4")) {
            return "次责";
        }
        return "未知";
    }

    /**
     * 动态设置Ratingbar高度，解决图片在不同分辨率手机拉伸问题
     *
     * @param context
     * @param ratingBar
     * @param resourceId 本地图片资源Id
     */
    public static void setRatingBarHeight(Context context, RatingBar ratingBar, int resourceId) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
        int height = bitmap.getHeight();
        ViewGroup.LayoutParams params = ratingBar.getLayoutParams();
        params.height = height;
        ratingBar.setLayoutParams(params);
    }

    //关闭软键盘
    public static void hideSoftKeyBoard(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(
                Context.INPUT_METHOD_SERVICE);
        if (null != imm) {
            imm.hideSoftInputFromWindow(((Activity) context).getWindow().
                    getDecorView().getWindowToken(), 0);
        }
    }

    //弹出软键盘
    public static void showSoftKeyBoard(Context context, EditText editText) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(
                Context.INPUT_METHOD_SERVICE);
        if (null != imm) {
            imm.showSoftInput(editText, 0);
        }
    }

    //重新计算布局的宽高
    public static int[] getViewSize(Context context, int resId, int padding) {
        //取得当前屏幕的长宽
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
        float screenWidth = dm.widthPixels;
        float screenHeight = dm.heightPixels;
        // 取得背景图片的大小
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(context.getResources(), resId, o);
        float bitmapWidth = o.outWidth;
        float bitmapHeight = o.outHeight;
        //实际缩放显示的宽高
        int width = (int) (screenWidth - UiUtil.dip2Px(padding) * 2);
        float scale = width / bitmapWidth;
        int height = Math.round(bitmapHeight * scale);

        return new int[]{width, height};
    }

    /**
     * 读取资源中的大图片
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap readBitmap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        //获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * 设置密码是否是明文
     */
    public static void setSeePwd(EditText editText) {
        if (editText != null) {
            TransformationMethod method = editText.getTransformationMethod();
            if (method instanceof PasswordTransformationMethod) {
                //可见
                editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                //隐藏
                editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            //移动光标到末尾
            editText.setSelection(editText.getText().toString().length());
        }
    }

    private static DisplayImageOptions options;

    //实例化imageloader的参数
    public static DisplayImageOptions getOptions() {
        if (null == options) {
            DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
            builder.showImageForEmptyUri(R.mipmap.download_fail1);
            builder.showImageOnFail(R.mipmap.download_fail);
            builder.showImageOnLoading(R.mipmap.reflash);
            builder.cacheInMemory(true);
            builder.cacheOnDisk(false);//磁盘缓存在版本升级后加载drawable下的图片会错位
            builder.imageScaleType(ImageScaleType.EXACTLY_STRETCHED);
            builder.bitmapConfig(Bitmap.Config.RGB_565);
            options = builder.build();
        }
        return options;
    }

    /**
     * 获取多少天之后的日期
     */
    public static long getDistanceDate(int days) {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, days);
        return c.getTime().getTime();
    }

    /**
     * 获取车牌的首字母简称
     *
     * @return
     */
    public static List<String> getCarnoShorts() {
        List<String> shorts = new ArrayList<String>();
        shorts.add("豫");
        shorts.add("京");
        shorts.add("津");
        shorts.add("冀");
        shorts.add("晋");
        shorts.add("蒙");
        shorts.add("辽");
        shorts.add("吉");
        shorts.add("黑");
        shorts.add("沪");
        shorts.add("苏");
        shorts.add("浙");
        shorts.add("皖");
        shorts.add("闽");
        shorts.add("赣");
        shorts.add("鲁");
        shorts.add("鄂");
        shorts.add("湘");
        shorts.add("粤");
        shorts.add("桂");
        shorts.add("琼");
        shorts.add("渝");
        shorts.add("川");
        shorts.add("贵");
        shorts.add("云");
        shorts.add("藏");
        shorts.add("陕");
        shorts.add("甘");
        shorts.add("青");
        shorts.add("宁");
        shorts.add("新");

        return shorts;
    }

    /**
     * 获取两个地理坐标点的实际距离
     *
     * @param paramLatLng1：起始坐标点
     * @param paramLatLng2：目的坐标点
     * @return
     */
    public static double getDistance(LatLng paramLatLng1, LatLng paramLatLng2) {
        if ((paramLatLng1 == null) || (paramLatLng2 == null))
            return -1.0D;
        Point localPoint1 = CoordUtil.ll2point(paramLatLng1);
        Point localPoint2 = CoordUtil.ll2point(paramLatLng2);
        if ((localPoint1 == null) || (localPoint2 == null))
            return -1.0D;
        return CoordUtil.getDistance(localPoint1, localPoint2);
    }

    public static Bitmap createPhotos(Bitmap bitmap) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            try {
                m.setRotate(90, bitmap.getWidth() / 2, bitmap.getHeight() / 2);//90就是我们需要选择的90度
                Bitmap bmp2 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
                bitmap = bmp2;
            } catch (Exception ex) {
                System.out.print("创建图片失败！" + ex);
            }
        }
        return bitmap;
    }

    /**
     * 压缩图片文件，回传文件路径
     *
     * @return
     */
    public static String bitmapNewWaH(String bImage, Context context) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(bImage, options);
        int width = options.outWidth;
        int height = options.outHeight;
        int scaleW = (height > width) ? height : width;
        //获取缩放比例
        int roundedSize = Math.round((float) scaleW / 640f);
        if (roundedSize < 1) {
            roundedSize = 1;
        }
        options.inSampleSize = roundedSize;
        options.inJustDecodeBounds = false;
        options.inTargetDensity = 1;

        Bitmap bitmap = BitmapFactory.decodeFile(bImage, options);
        int realW = bitmap.getWidth();
        int realH = bitmap.getHeight();
        //判断图片是竖屏还是横屏 获取新的宽高
        if (realH > realW) {
            bitmap = createPhotos(bitmap);
        }
        Bitmap newbitmap = Util.fitBitmap(bitmap, 640);
        byte[] bytes = BitmaptoBytes(newbitmap);
        String path = SavePicturetoSdcard(bytes, context);
        return path;
    }

    // 保存相片到sdcard
    private static String SavePicturetoSdcard(byte[] data, Context context) {
        boolean success = false;
        try {
            if ((data != null) && (!data.equals("")) && (data.length > 0)) {
                String dir = FileUtils.getDir("KCKP", context);
                File file = new File(dir, FileUtils.dateformaterfilename());
                String absolutePath = file.getAbsolutePath();//照片的存储路径
                boolean writeFileissuccess = FileUtils.writeFile(data, absolutePath, false);// 将文件写入到SD卡下
                success = writeFileissuccess;
                return absolutePath;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 处理url字符串中的中文和空格
     *
     * @param url
     * @return
     */
    public static String encodeUrlString(String url) {
        String temp = null;
        try {
            //转化汉字和空格
            temp = URLEncoder.encode(url, "UTF-8").replaceAll("\\+", "%20");
            //还原链接中的特殊符号
            temp = temp.replaceAll("%3A", ":").replaceAll("%2F", "/");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return temp;
    }

    /**
     * 获取天气对应的图标
     *
     * @param name
     * @return
     */
    public static int getWeacherIcon(String name) {
        if (name.startsWith("晴")) {
            return R.mipmap.wea_qingtian;
        } else if (name.startsWith("多云")) {
            return R.mipmap.wea_duoyun;
        } else if (name.startsWith("阴")) {
            return R.mipmap.wea_yintian;
        } else if (name.startsWith("雷阵雨")) {
            return R.mipmap.wea_leizhenyu;
        } else if (name.startsWith("雷阵雨伴有冰雹")) {
            return R.mipmap.wea_yujiabingbao;
        } else if (name.startsWith("雨夹雪")) {
            return R.mipmap.wea_yujiaxue;
        } else if (name.startsWith("小雨") || name.startsWith("阵雨")) {
            return R.mipmap.wea_xiaoyu;
        } else if (name.startsWith("中雨")) {
            return R.mipmap.wea_zhongyu;
        } else if (name.startsWith("大雨")) {
            return R.mipmap.wea_dayu;
        } else if (name.startsWith("暴雨") || name.startsWith("大暴雨")) {
            return R.mipmap.wea_baoyu;
        } else if (name.startsWith("特大暴雨")) {
            return R.mipmap.wea_tedabaoyu;
        } else if (name.startsWith("小雪") || name.startsWith("阵雪")) {
            return R.mipmap.wea_xiaoxue;
        } else if (name.startsWith("中雪")) {
            return R.mipmap.wea_zhognxue;
        } else if (name.startsWith("大雪")) {
            return R.mipmap.wea_daxue;
        } else if (name.startsWith("暴雪")) {
            return R.mipmap.wea_dabaoxue;
        } else if (TextUtils.equals(name, "雾")) {
            return R.mipmap.wea_wu;
        } else if (TextUtils.equals(name, "浮尘")) {
            return R.mipmap.wea_fuchen;
        } else if (TextUtils.equals(name, "扬沙")) {
            return R.mipmap.wea_shachen;
        } else if (TextUtils.equals(name, "沙尘暴")) {
            return R.mipmap.wea_shachenbao;
        } else if (TextUtils.equals(name, "霾")) {
            return R.mipmap.wea_wumai;
        } else if (name.startsWith("风")) {
            return R.mipmap.wea_feng;
        } else if (name.startsWith("大风")) {
            return R.mipmap.wea_dafeng;
        } else if (name.startsWith("飓风")) {
            return R.mipmap.wea_jufeng;
        } else {
            return R.mipmap.wea_weizhi;
        }
    }

    public static String getPeccancyStr(String type) {
        if (TextUtils.equals(type, "0")) {
            return "逆行";
        } else if (TextUtils.equals(type, "1")) {
            return "强行加塞";
        } else if (TextUtils.equals(type, "2")) {
            return "骑压实线、导流线";
        } else if (TextUtils.equals(type, "3")) {
            return "闯红灯";
        } else if (TextUtils.equals(type, "4")) {
            return "违章停车";
        }
        return "违章行为";
    }

    public static String getImgTypeStr(String type) {
        if (TextUtils.equals(type, "31")) {
            return "车辆及禁停标志、标线";
        } else if (TextUtils.equals(type, "32")) {
            return "车辆及地标性建筑";
        } else if (TextUtils.equals(type, "33")) {
            return "车牌号照片";
        } else if (TextUtils.equals(type, "34")) {
            return "驾驶证照片";
        } else if (TextUtils.equals(type, "35")) {
            return "违章行为";
        } else if (TextUtils.equals(type, "30")) {
            return "补充说明图片";
        }
        return "补充说明图片";
    }

    private static final String NAME = "[\u4e00-\u9fa5]{2,16}"; //检测是否是中文名（长度最大16位）
    private static final String ACCOUNT = "^(?![0-9]+$)[0-9A-Za-z]{6,10}$";//由6到10位的字母和数字组成,不能为纯数字
    private static final String BANKNUM = "^[0-9]+$";//纯数字,银行卡号不限制位数
    private static final String PWD = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,15}$";//由6到15位的字母和数字组成,不能为纯数字或字母
    private static final String CARVIN = "^[a-zA-Z0-9]{17}$"; // 车架VIN正则
    private static final String ENGINE = "^[a-zA-Z0-9]+$"; // 发动机号正则

    public static boolean isChinaName(String name) {
        if (TextUtils.isEmpty(name)) {
            return false;
        }
        return Pattern.compile(NAME).matcher(name).matches();
    }

    public static boolean isAccount(String account) {
        if (TextUtils.isEmpty(account)) {
            return false;
        }
        return Pattern.compile(ACCOUNT).matcher(account).matches();
    }

    public static boolean isBank(String banknum) {
        if (TextUtils.isEmpty(banknum)) {
            return false;
        }
        return Pattern.compile(BANKNUM).matcher(banknum).matches();
    }

    public static boolean isPassword(String pwd) {
        if (TextUtils.isEmpty(pwd)) {
            return false;
        }
        return Pattern.compile(PWD).matcher(pwd).matches();
    }

    public static boolean isCarvin(String carvin) {
        if (TextUtils.isEmpty(carvin)) {
            return false;
        }
//        return Pattern.compile(CARVIN).matcher(carvin).matches();
        return true;
    }

    public static boolean isEngine(String engine) {
        if (TextUtils.isEmpty(engine)) {
            return false;
        }
        return Pattern.compile(ENGINE).matcher(engine).matches();
    }
}


